<?php 

  namespace App\Http\Controllers\Service;

  use App\Http\Controllers\Controller;

  //引入状态输出类

  use App\Models\M3Result;

  use Illuminate\Http\Request;

  use Illuminate\Http\Response;

  use App\Entity\Cart;

  /**

  * coder:zhengchengjun

  * time:2017-8-19

  * function:购物车类

  */

  class CartController extends Controller{

    /**

     *  添加购物车 中商品

     * @param [type] $pid [产品Id]

     */

    public function addCart(Request $request,$product_id){
      $result=new M3Result();
      //获得cookie购物  车字符串

      $cart=$request->cookie('cart','');

      //把cookie字符串解析 Like: pid:count |   1:2,9:10

      $cart=$cart?explode(',',$cart):array();

      $uid=$request->session()->get('member');

      //存在cookie中的购物车可能会过期，所以还要读取一下数据库看是不是

      //真的没了

      if(!$cart){

        $cartDb=new Cart;

        $id=$cartDb->where('mid',$uid)->pluck('id');

        //在数据库中存在

        if($id){

          //把数据库中的数据取出来，组成新的cookie字符串

          $cart=$cartDb->where('mid',$uid)->get();

          $cartMiddle=array();

          foreach($cart as $k=>$v){

            $value=$v['pid'].':'.$v['count'];

            array_push($cartMiddle,$value);

          }

          //重组完成

          $cart=$cartMiddle;

        }

      }

      //购物车数量默认等于1

      $count=1;

      //这是给己存在购物车中的商品进行增量用的

      foreach($cart as $k=>$v){
        $cartDb=new Cart;
        //找到:的位置，在它左边的是产品id右边的是数量

        $index=strpos($v,':');

        $pid=substr($v,0,$index);

        //找到指定产品购物车数量加1

        $pid=(int)$pid;

        if($pid==$product_id){

          $count=substr($v,$index+1);

          $count=(int)$count;

          $count++;

          
          //规格处理
          $specifications=$request->input('data','');
          //商品存在规格
          if($specifications){        
            $cartDb=Cart::where('mid',$uid)->where('pid',$pid)->first();
            $specificationsResult=[];
            foreach ($specifications as $key => $value) {
              array_push($specificationsResult,$key.':'.$value);
            } 
            $specificationsResult=implode(',',$specificationsResult);
            $uid=$request->session()->get('member');
            $cartDb->specifications=$specificationsResult;
            $cartDb->save();
          }


          $cartDb->where('pid',$pid)->where('mid',$uid)->increment('count');

          $cart[$k]=$pid.':'.$count;

          break;

        }

      }

      //添加的是购物车中不存在的的商品

      if($count==1){

        //给购物车数组更新

        array_push($cart,$product_id.':'.$count);
          //规格处理
          $specifications=$request->input('data','');
          //商品存在规格
          if($specifications){        
            $specificationsResult=[];
            foreach ($specifications as $key => $value) {
              array_push($specificationsResult,$key.':'.$value);
            } 
            $specificationsResult=implode(',',$specificationsResult);
            $this->syncCart($product_id,1,$uid,true,$specificationsResult);
          }else{
            $this->syncCart($product_id,1,$uid,true);
          }                                        
      }

      $result->status=1;

      $result->message='商品添加成功';

      $response = new \Illuminate\Http\Response($result->toJson());

      $response->withCookie(cookie('cart',implode(',',$cart),1440));

      return $response;

    }

    /**

     * 移除购物车，就是把cookie删了

     * @param  Request $request [description]

     * @return [type]           [description]

     */

    public function removeCart(Request $request,$pid){

      $result=new M3Result();

      $uid=$request->session()->get('member');

      $cart=$request->cookie('cart');

      //要移除出购物车的中的商品id

      $remove=explode(',',$pid);

      //把cookie字符串解析 Like: pid:count |   1:2,9:10

      $cart=$cart?explode(',',$cart):array();

      if(!$cart){

        $cartDb=new Cart;

        $id=$cartDb->where('mid',$uid)->pluck('id');

        //在数据库中存在

        if($id){

          //把数据库中的数据取出来，组成新的cookie字符串

          $cart=$cartDb->where('mid',$uid)->get();

          $cartMiddle=array();

          foreach($cart as $k=>$v){

            $value=$v['pid'].':'.$v['count'];

            array_push($cartMiddle,$value);

          }

          //重组完成

          $cart=$cartMiddle;

        }

      } 

      foreach($cart as $k=>$v){

        $index=strpos($v,':');

        $pid=substr($v,0,$index);

        if(in_array($pid,$remove)){

          $key=array_search($v,$cart);

          unset($cart[$key]);

          $uid=$request->session()->get('member');

          $this->syncCart($pid,0,$uid,false);

        }

      }

      $result->status=1;

      $result->message='商品移除成功';

      $response = new \Illuminate\Http\Response($result->toJson());

      $response->withCookie(cookie('cart',implode(',',$cart),-1));

      return $response;          

    }

    //同步数据库加入一条初始数据

    public function syncCart($pid,$count=0,$uid=0,$flag=false,$specifications=''){

     $cart=new Cart;

     if ($flag==true) {

       $cart->pid=$pid;

       $cart->count=$count;

       $cart->mid=$uid;
       if($specifications){
         $cart->specifications=$specifications;
       }

       $cart->save();

     }else{

      $cart->where('pid',$pid)->where('mid',$uid)->delete();

     }

    }

    public function test(){

 $response = new \Illuminate\Http\Response('hello');

      $response->withCookie(cookie('cart','',-1));

      return $response;    

    }

  }

 ?>

